﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
using ZK.Common;

namespace ZK.HardWareBLL
{
    /// <summary>
    /// 泥人网络继电器 I201
    /// </summary>
    public class NRNetRelayBLL
    {
        HaredWareCommonM haredWareCommonM;
        Socket client;

        public NRNetRelayBLL()
        {
            haredWareCommonM = IConfig.GetSetNRNetRelay;
        }
        //stach begin 1 2 3 4 5 6 ..................
        public bool HandleStach(int num)
        {
            try
            {
                ///创建客户端
                client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);
                ///IP地址
                IPAddress ip = IPAddress.Parse(haredWareCommonM.Ip);
                ///端口号
                IPEndPoint endPoint = new IPEndPoint(ip, int.Parse(haredWareCommonM.Port));
                ///建立与服务器的远程连接
                client.Connect(endPoint);
                ///线程问题
                //Thread thread = new Thread(ReciveMsg);
                //thread.IsBackground = true;
                //thread.Start(client);
                //将字符串指令转换为byte数组
                byte[] buf = System.Text.Encoding.Default.GetBytes("AT+STACH" + num + "=1,1\r\n");
                //发送AT指令
                client.Send(buf);

                byte[] recbuf = new byte[10];//真正使用时，接收缓冲区需要适当的调整
                                             //等待硬件响应命令，接收到的数据为byte数组
                                             //会等待到有数据返回为止
                int recLen = client.Receive(recbuf);
                client.Close();
                //将byte数组转为字符串
                string str = System.Text.Encoding.Default.GetString(recbuf);
                str = str.Replace("\r\n", "").Trim().ToLower();
                if (!str.Contains("ok"))
                {
                    Common.Log4.LogManage.WriteErr(str);
                    Common.DelegateHelper.InfoMessageEvent?.Invoke(str);
                    return false;
                }
                return true;
            }
            catch (Exception ex)
            {
                Common.Log4.LogManage.WriteErr(ex.ToString());
                Common.DelegateHelper.InfoMessageEvent?.Invoke(ex.Message);
                return false;
            }

        }
    }
}
